/**
 *  通过主机名获取信息
 *  /etc/hosts 内容如下
 *      192.168.118.130 gino gino1 gino2 gino3
 *      127.0.0.1       gino
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>

void print_hostent(struct hostent *hostinfo)
{
    int i = 0;

    printf("hostname: %s\n", hostinfo->h_name);
    printf("addrtype: %s\n", hostinfo->h_addrtype == AF_INET ? "IPv4" : "IPv6");
    printf("ip address: ");
    for (; hostinfo->h_addr_list[i] != NULL; ++i)
    {
        char ip[64] = {0};
        inet_ntop(hostinfo->h_addrtype, hostinfo->h_addr_list[i],
                  ip, sizeof(ip));
        printf("%s ", ip);
    }
    printf("\n");

    for (i = 0; hostinfo->h_aliases[i] != NULL; ++i)
    {
        printf("aliase: %s\n", hostinfo->h_aliases[i]);
    }
}

int main(int argc, char **argv)
{
    if (2 > argc)
    {
        fprintf(stderr, "%s <hostname>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    struct hostent *hostinfo = NULL;

    while ((hostinfo = gethostent()) != NULL)
    {
        if (strncmp(argv[1], hostinfo->h_name, strlen(hostinfo->h_name)) == 0)
        {
            print_hostent(hostinfo);
        }
    }

    return 0;
}